package com.baosight.risk.service.riim.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baosight.risk.service.rifi.entity.RifiRiskFinish;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.fltd.FltdTaskService;
import com.baosight.risk.api.riaa.RiaaQuesInquiryService;
import com.baosight.risk.api.rifi.RifiRiskFinishService;
import com.baosight.risk.api.riim.RiimRiskImportExService;
import com.baosight.risk.api.riim.RiimRiskImportService;
import com.baosight.risk.api.workflow.AfterHandler;
import com.baosight.risk.api.workflow.UpdateHandler;
import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.api.xtzy.IXtzyUserService;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.enums.Status;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.DateUtils;
import com.baosight.risk.common.utils.ShiroUtils;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.riim.RiimRiskAssignmentMapper;
import com.baosight.risk.mapper.riim.RiimRiskEvaluationMapper;
import com.baosight.risk.mapper.riim.RiimRiskGoalDetailMapper;
import com.baosight.risk.mapper.riim.RiimRiskGoalMapper;
import com.baosight.risk.mapper.riim.RiimRiskImportMapper;
import com.baosight.risk.mapper.rire.RireRiskTargetMapper;
import com.baosight.risk.mapper.rire.RireRiskWarningStatusMapper;
import com.baosight.risk.mapper.riri.RiriDutyCompMapper;
import com.baosight.risk.mapper.riri.RiriDutyUserMapper;
import com.baosight.risk.mapper.riri.RiriRiskMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringRuleMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringStatusMapper;
import com.baosight.risk.mapper.riwa.RiwaRiskWaringTargetMapper;
import com.baosight.risk.mapper.xtaa.code.XtaaCodeMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompanyMapper;
import com.baosight.risk.service.fltd.entity.FltdTask;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.quartz.entity.SyncEmpleeEntitiy;
import com.baosight.risk.service.rifi.vo.RifiFinishVO;
import com.baosight.risk.service.riim.entity.RiimRiskAssignment;
import com.baosight.risk.service.riim.entity.RiimRiskEvaluation;
import com.baosight.risk.service.riim.entity.RiimRiskGoal;
import com.baosight.risk.service.riim.entity.RiimRiskGoalDetail;
import com.baosight.risk.service.riim.entity.RiimRiskImport;
import com.baosight.risk.service.riim.vo.RiimRiskGoalVO;
import com.baosight.risk.service.riim.vo.RiimRiskImportVO;
import com.baosight.risk.service.rire.entity.RireRiskTarget;
import com.baosight.risk.service.rire.entity.RireRiskWarningStatus;
import com.baosight.risk.service.rire.vo.RiskWarningStatusVO;
import com.baosight.risk.service.riri.entity.RiriDutyComp;
import com.baosight.risk.service.riri.entity.RiriDutyUser;
import com.baosight.risk.service.riri.entity.RiriRisk;
import com.baosight.risk.service.riri.impl.RiaaRiskServiceImpl;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaring;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringRule;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringStatus;
import com.baosight.risk.service.riwa.entity.RiwaRiskWaringTarget;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.xtaa.code.entity.XtaaCode;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.baosight.risk.web.freemarker.FreeMarkerController;

import lombok.extern.slf4j.Slf4j;

@Service("riimRiskImportServiceImpl")
@Slf4j
public class RiimRiskImportServiceImpl extends BaseServiceImpl<RiimRiskImport> implements RiimRiskImportService, UpdateHandler, AfterHandler {

    @Autowired
    private RiimRiskImportMapper riskImportMapper;
    @Autowired
    private RiimRiskAssignmentMapper assignmentMapper;
    @Autowired
    private RiimRiskEvaluationMapper evaluationMapper;
    @Autowired
    private RiimRiskGoalMapper goalMapper;
    @Autowired
    private RiaaRiskServiceImpl riaaRiskService;
    @Autowired
    private RiimRiskGoalDetailMapper goalDetailtMapper;
    @Autowired
    private RiriDutyUserMapper dutyUserMapper;
    @Autowired
    private RiriDutyCompMapper dutyCompMapper;
    @Autowired
    private RiriRiskMapper ririRiskMapper;

    @Autowired
    private IXtzyCompanyService xtzyCompanyService;

    @Autowired
    private RiimRiskImportService importService;

    @Autowired
    private RifiRiskFinishService finishService;

    @Autowired
    private FreeMarkerController freeMarkerController;

    @Autowired
    private FltdProcessService fltdProcessService;
    @Autowired
    private FltdTaskService fltdTaskService;
    @Autowired
    private RireRiskWarningStatusMapper rireRiskWarningStatusMapper;

    @Autowired
    private RireRiskTargetMapper rireRiskTargetMapper;

    @Autowired
    private RiwaRiskWaringMapper riskWaringMapper;
    @Autowired
    private RiwaRiskWaringStatusMapper riskWaringStatusMapper;
    @Autowired
    private RiwaRiskWaringRuleMapper riskWaringRuleMapper;
    @Autowired
    private RiwaRiskWaringTargetMapper riskWaringTatgetMapper;

    @Autowired
    private XtzyCompanyMapper companyMapper;

    @Autowired
    private XtaaCodeMapper xtaaCodeMapper;

    @Autowired
    private RiaaQuesInquiryService riaaQuesInquiryService;

    //主责单位
    private static String dutyComp = "T_RIIM_RISK_IMPORT.DUTY_COMP_CODE";
    //负责单位
    private static String auxiliaryComp = "T_RIIM_RISK_IMPORT.AUXILIARY_COMP_CODE";
    //主责领导
    private static String dutyLead = "T_RIIM_RISK_IMPORT.DUTY_LEAD_CODE";
    //主责领导
    private static String exeLead = "T_RIIM_RISK_IMPORT.EXE_LEAD_CODE";
    @Autowired
    private IXtzyUserService xtzyUserService;
    @Autowired
    private RiimRiskImportExService riimRiskImportExService;

    @Override
    public BaseMapper getMapper() {
        return riskImportMapper;
    }

    @Override
    public List<RiimRiskImport> selectList(RiimRiskImportVO riskImport, XtzyUser user) {
//        if (StringUtils.isEmpty(riskImport.getAcctYear())){
//            riskImport.setAcctYear(DateUtils.format(new Date(),"yyyy"));
//        }else {
//            riskImport.setAcctYear(riskImport.getAcctYear().substring(0,4));
//        }


        if (!ShiroUtils.getUser().isAdmin()) {
            List<XtzyCompany> parantAndChildrens = xtzyCompanyService.getParantAndChildrens(user.getExt1());
            List<String> deptList = parantAndChildrens.stream().map(XtzyCompany::getCompCode).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(deptList)) {
                riskImport.setDutyCompListStr(deptList);
            }

        }

        if (StringUtils.isNotEmpty(riskImport.getAcctYear())) {
            riskImport.setAcctYear(riskImport.getAcctYear().substring(0, 4));
        }
//        if (!ShiroUtils.getUser().isAdmin()) {
//            riskImport.setCompIdList(riaaRiskService.getCompCodes(user.getExt1(), riskImport.getExt5()));
//        }
        servicePage();
        //处理查询结果筛选异常
        String acctYear = riskImport.getAcctYear();
        String isOverTheYears = riskImport.getIsOverTheYears();
        if (isOverTheYears != null){
            if (acctYear == null && riskImport.getIsOverTheYears().equals("N")){
                riskImport.setIsOverTheYears("allN");
            }
        }
        List<RiimRiskImport> list = riskImportMapper.selectList(riskImport);
        if (BeanUtils.sortList(list)) {
            for (RiimRiskImport riimRiskImport : list) {
                RiimRiskImport param = new RiimRiskImport();
                param.setId(riimRiskImport.getId());
                param.setRowOrder(riimRiskImport.getRowOrder());
                riskImportMapper.updateByPrimaryKeySelective(param);
            }
        }
        return list;
    }

    @Override
    public List<RiimRiskImport> queryShiShi(RiimRiskImportVO riskImport) {
        //实施方案查询专用
        riskImport.setExt1("实施方案");
        if (StringUtils.isNotEmpty(riskImport.getDeptCode())) {
            List<XtzyCompany> parantAndChildrens = xtzyCompanyService.getParantAndChildrens(riskImport.getDeptCode());
            List<String> deptList = parantAndChildrens.stream().map(XtzyCompany::getCompCode).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(deptList)) {
                riskImport.setCompIdList(deptList);
            }
        }
        if (CollectionUtils.isNotEmpty(riskImport.getCompIdList())) {
            riskImport.getCompIdList().add(riskImport.getDeptCode());
            riskImport.setDeptCode(null);
        }
        return riskImportMapper.selectList(riskImport);
    }

    @Override
    public Integer saveImportByRisk(List<RiriRisk> ririRiskList) throws Exception {
        for (RiriRisk ririRisk : ririRiskList) {
        	RiimRiskImport riskImport = insertImportByRisk(ririRisk);
        	//复制到各基地
            riimRiskImportExService.copyToSub(riskImport);
        }
        return 1;

    }

    public RiimRiskImport insertImportByRisk(Object object) throws Exception {
        RiimRiskImport riskImport = new RiimRiskImport();
        BeanUtils.copyBeanProp(riskImport, object);
        //置空季度
        riskImport.setQuarterCurrent("");
//        riskImport.setRiaaRiskNo(ririRisk.getRiaaRiskNo());
//        riskImport.setRiskId(ririRisk.getId());
        if (object instanceof RiriRisk) {
            riskImport.setRiskId(((RiriRisk) object).getId());
        }
        if (StringUtils.isEmpty(riskImport.getManageCompCode())) {
            XtzyCompany company1 = companyMapper.getCompanyInfo(ShiroUtils.getUser().getExt1());
            XtzyCompany company2 = companyMapper.getCompByCompCode(company1.getPathCode());
            riskImport.setManageCompCode(company2.getCompCode());
            riskImport.setManageCompName(company2.getCompName());
        }
        riskImport.setStatus(Status.DRAFT.getValue());
        riskImport.setStatusName(Status.DRAFT.getDescription());
        riskImport.setFinishStatus("A01");
        riskImport.setFinishStatusName("草稿");
        riskImport.setSpecialFlag("N");
        Integer rowOrder;
        Integer maxRowOrder = riskImportMapper.queryMax(riskImport.getAcctYear(), riskImport.getManageCompCode());
        if (maxRowOrder == null) {
            rowOrder = 1;
        } else {
            rowOrder = Integer.valueOf(maxRowOrder) + 1;
        }
        riskImport.setRowOrder(rowOrder);
        RiimRiskImportVO riimRiskImport = new RiimRiskImportVO();
        riimRiskImport.setAcctYear(riskImport.getAcctYear());
        riimRiskImport.setRiskName(riskImport.getRiskName());
        riimRiskImport.setDeptCode(riskImport.getDeptCode());
//            riimRiskImport.setSpecialFlag("N");
        List<RiimRiskImport> list = new ArrayList<RiimRiskImport>();
        if("BGTA".equals(riskImport.getManageCompCode())){
            list=selectList(riimRiskImport, null);
        }else{
            list=selectList(riimRiskImport, getUser());
        }
        if (StringUtils.isNotEmpty(list)) {
            throw new Exception(riskImport.getAcctYear() + "年【" + riskImport.getDeptName() + "】该组织下已存在重点风险名称为：【" + riskImport.getRiskName() + "】的重点风险！");
        } else {
            riskImport = (RiimRiskImport) BeanUtils.initBean(riskImport);
            riskImportMapper.insert(riskImport);
        }
        return riskImport;
    }

    @Override
    public List<RiimRiskImport> getByIds(List<String> ids) {
        return riskImportMapper.getByIds(ids);
    }


    @Override
    public Integer updateRiskImport(RiimRiskImport riskImport) {
        return riskImportMapper.updateByPrimaryKeySelective(riskImport);
    }

    @Override
    public void saveImportList(List<String> riskNoList) throws Exception {
        //找到去年全年未关闭的数据
        //获取去年的年份
        String year = DateUtils.format(new Date(), "yyyy");
        Integer lastYesr = Integer.valueOf(year) - 1;
        List<String> statusList = new ArrayList<>();
        //状态执行中
        statusList.add("01");
        statusList.add("02");
        List<RiimRiskImport> lastImportList = riskImportMapper.selectByYearStatusList(lastYesr.toString(), statusList, riskNoList);
        List<RiimRiskImport> currentImportList = riskImportMapper.selectByYearStatusList(year, statusList, null);
        // 已经有的重点风险不要带过来
        List<RiimRiskImport> importList = new ArrayList<>();
        for (RiimRiskImport lastRiimRiskImport : lastImportList) {
            boolean flag = false;
            for (RiimRiskImport currentRiimRiskImport : currentImportList) {
                if (currentRiimRiskImport.getRiskNo().equals(lastRiimRiskImport.getRiskNo())) {
                    flag = true;
                    break;
                }
            }
            if (!flag) {
                importList.add(lastRiimRiskImport);
            }
        }

        if (CollectionUtils.isEmpty(importList)) {
            log.error("没有数据可以流转！");
            throw new Exception("没有数据可以流转！");
        }
        for (RiimRiskImport riskImport : importList) {
            RiimRiskImport riskImport1 = new RiimRiskImport();
            BeanUtils.copyBeanProp(riskImport1, riskImport);
            riskImport1.setCirculationId(riskImport.getId());
            importInfo(riskImport1);
            riskImport1 = (RiimRiskImport) BeanUtils.initBean(riskImport1);
//            if (null!=riskImport1.getIsOverTheYears()&&riskImport1.getIsOverTheYears().equals("Y")){
//                continue;
//            }
            riskImportMapper.insert(riskImport1);
            //新增后，如果有上年的重点风险有披露报告，原引上年
//            reportService.saveByLastYear(riskImport.getId(),riskImport1.getId(),String.valueOf(Integer.valueOf(DateUtils.getQuarter())-1));
        }
    }

    public void importInfo(RiimRiskImport riskImport1) {
        riskImport1.setStatus("02");
        riskImport1.setStatusName("执行中");
        riskImport1.setAcctYear(DateUtils.format(new Date(), "yyyy"));
        riskImport1.setQuarterCurrent(DateUtils.getQuarter(new Date()));
        //数据初始值
        riskImport1.setDutyCompCode(null);
        riskImport1.setDutyCompName(null);
        riskImport1.setAuxiliaryCompCode(null);
        riskImport1.setAuxiliaryCompName(null);
        riskImport1.setDutyLeadCode(null);
        riskImport1.setDutyLeadName(null);
        riskImport1.setExeLeadCode(null);
        riskImport1.setExeLeadName(null);
        riskImport1.setAdvanceMechanism(null);
        riskImport1.setTrainNeed(null);
        riskImport1.setDutyUserCode(null);
        riskImport1.setDutyUserName(null);
        riskImport1.setGroupUserCode(null);
        riskImport1.setGroupUserName(null);
        riskImport1.setDeptUserCode(null);
        riskImport1.setDeptUserName(null);
        riskImport1.setAuditDate(null);
        riskImport1.setFinishStatus(null);
        riskImport1.setFinishStatusName(null);
        riskImport1.setRemark(null);
        riskImport1.setTelephone(null);
        riskImport1.setUpdateFlag("0");
        riskImport1.setPlanStatus(null);
        riskImport1.setPlanStatusName(null);
    }


    @Override
    public Boolean saveSendList(List<RiimRiskImport> riskImportList) throws Exception {
        String flag="";
        List<XtaaCode> list = new ArrayList<>();
        list   =  xtaaCodeMapper.selectAllDataByDDTypeCode("isSendToDo");
        for (int i= 0;i<list.size();i++){
            XtaaCode code1 = list.get(i);
            if (code1.getStatus().equals("10")){
                flag = code1.getDdCode();
                break;
            }
        }
        if (flag.equals("open")){
            if (StringUtils.isNotEmpty(riskImportList)) {

                savePone(riskImportList);
            } else {

                // 前端未勾选数据，则将当前年度，季度的重点风险进行刷选启动方案编制
                RiimRiskImportVO riskImport = new RiimRiskImportVO();
                //获取今年的年份
//            String year = DateUtils.format(new Date(),"yyyy");
//            riskImport.setAcctYear(year);
                List<RiimRiskImport> importList = riskImportMapper.selectList(riskImport);
                savePone(importList);

            }

        }
        return true;


    }
    public Boolean saveSingleReport(String id) throws Exception{
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        int startNum = 0;
        try{
        RiimRiskImportVO riskImport = new RiimRiskImportVO();
        riskImport.setId(id);
        //找到年度重点风险，然后生成披露报告
        List<RiimRiskImport> importList = riskImportMapper.selectList(riskImport);

        //接待办
        FltdTaskVO taskVO = new FltdTaskVO();
        String flowNo = "";
        if (CollectionUtils.isNotEmpty(importList)) {
            for (RiimRiskImport riimRiskImport : importList) {
                if("BGTA".equals(riimRiskImport.getManageCompCode())){
                    flowNo="fengxianpilubaogao";
                    taskVO.setFlowNo(flowNo);
                    taskVO.setFlowName("重点风险披露报告");
                }else{
                    flowNo = "jidifengxianpilubaogao";
                    taskVO.setFlowNo(flowNo);
                    taskVO.setFlowName("重点风险披露报告（基地）");
                }

                taskVO.setAcctYear(riimRiskImport.getAcctYear());
                taskVO.setQuarterCode(riimRiskImport.getQuarterCurrent());
                taskVO.setQuarterName(DateUtils.getQuarterName("1"));
                //生成披露报告
                RireRiskWarningStatus warningStatus = new RireRiskWarningStatus();
                warningStatus.setImportGuid(riimRiskImport.getId());
                warningStatus.setAcctYear(riimRiskImport.getAcctYear());
                warningStatus.setQuarterCode("1");
                warningStatus.setEditPerson(riimRiskImport.getDutyUserName());
                warningStatus.setRowOrder(riimRiskImport.getRowOrder());
                warningStatus.setStrategy(riimRiskImport.getRemark());
                warningStatus.setWaringStatus("");//为了首页展示数据
                warningStatus.setNextWaringStatus("");//为了首页展示数据
                List<RiskWarningStatusVO> statusList = rireRiskWarningStatusMapper.selectList(warningStatus, null);
                //根据年度、季度、重点风险ID 找披露报告,如果找到，表示已经下发过，不再下发
                //如果存在披露报告，但是没有待办，直接发起流程不添加披露报告记录
                boolean flag = false;
                if (CollectionUtils.isNotEmpty(statusList)) {
                    RireRiskWarningStatus report = statusList.get(0);
                    FltdTask task = new FltdTask();
                    task.setFlowNo(flowNo);
                    task.setAcctYear(riimRiskImport.getAcctYear());
                    task.setQuarterCode("1");
                    task.setDeptCode(riimRiskImport.getDeptCode());
                    task.setTaskGuid(riimRiskImport.getId());
                    FltdTask fltdTask = fltdTaskService.selectExistTask(task);
                    if (fltdTask != null) {
                        continue;
                    } else {
                        flag = true;
                    }
                }
                if (!flag) {
                    warningStatus.setQuarterName(DateUtils.getQuarterName("1"));
                    warningStatus.setRiskId(riimRiskImport.getRiskId());

                    warningStatus.setStatus("A01");
                    warningStatus.setStatusName("待填报");
                    warningStatus.setManageCompCode(riimRiskImport.getManageCompCode());
                    warningStatus.setManageCompName(riimRiskImport.getManageCompName());
                    warningStatus = (RireRiskWarningStatus) BeanUtils.initBean(warningStatus);
                    rireRiskWarningStatusMapper.insert(warningStatus);
                    // 将上一季度披露报告的风险指标和预警模型带到本季度
                    List<RiimRiskImport> riimRiskImportList = riskImportMapper.selectCheck(riimRiskImport.getRiskNo(), "", String.valueOf(Integer.parseInt(riimRiskImport.getAcctYear())-1));
                    if (CollectionUtils.isNotEmpty(riimRiskImportList)) {
                        RiimRiskImport pastRiimRiskImport = riimRiskImportList.get(0);
//                            warningStatus.setImportGuid(pastRiimRiskImport.getId());
                        insertData(warningStatus, pastRiimRiskImport);
                    }
                    taskVO.setBizGuid(warningStatus.getId());
                } else {
                    RireRiskWarningStatus report = statusList.get(0);
                    taskVO.setBizGuid(report.getId());
                }

                //填充工作流需要的数据
                XtzyCompany company = new XtzyCompany();
                company.setCompCode(riimRiskImport.getDeptCode());
                company.setCompName(riimRiskImport.getDeptName());
                taskVO.setCustomCompany(company);
                taskVO.setCompCode(riimRiskImport.getCompCode());
                taskVO.setCompName(riimRiskImport.getCompName());
                taskVO.setDeptCode(riimRiskImport.getDeptCode());
                taskVO.setDeptName(riimRiskImport.getDeptName());
                String bizDesc = taskVO.getAcctYear() + "年度-" + taskVO.getQuarterName() + "-<" + riimRiskImport.getRiskName() + ">-重点风险披露报告";
                taskVO.setBizName(bizDesc);
                taskVO.setBizDesc(bizDesc);
                taskVO.setTaskGuid(riimRiskImport.getId());
                taskVO.setManageCompCode(riimRiskImport.getManageCompCode());
                taskVO.setManageCompName(riimRiskImport.getManageCompName());
                taskVO.setGroupCondition(taskVO.getAcctYear() + "1");
                try {
                    startNum++;
                    //启动流程
                    fltdProcessService.doStart(taskVO);
                    logs.add(fltdProcessService.getLog("重点风险披露报告-流程启动成功", 0, "业务id：" + warningStatus.getId() + "，重点风险id：" + riimRiskImport.getId(), id));
                } catch (Exception e) {
                    logs.add(fltdProcessService.getLog("重点风险披露报告-流程启动失败", 1, e.getMessage(), id));
                    error = e;
                    break;
                }
            }
        }

        //找到当年所有重点风险

        if (startNum == 0) {
            logs.add(fltdProcessService.getLog("重点风险披露报告-流程启动成功", 1, "未查到可以下发的重点风险数据", id));
        }
    } catch (Exception e) {
        logs.add(fltdProcessService.getLog("重点风险披露报告-下发失败", 1, e.getMessage(), id));
        error = e;
    }
    // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
        throw error;
    }
        return true;
    }

    @Override
    public Boolean saveSendReport(String jobParam, String manageCompCode,String jobId) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        int startNum = 0;
        try {
            String year = "";
            String pastYear = "";
            Integer quarterCurrent = 0;
            if (StringUtils.isNotEmpty(jobParam) && jobParam.indexOf(",") > 1) {
                String[] split = jobParam.split(",");
                year = split[0];
                quarterCurrent = Integer.parseInt(split[1]);
            } else {
                //获取今年的年份
                year = DateUtils.format(new Date(), "yyyy");
                //获取当季度
                quarterCurrent = Integer.valueOf(DateUtils.getQuarter(new Date()));

            }
            if (1 == quarterCurrent) {
                pastYear = String.valueOf(Integer.valueOf(year) - 1);
            } else {
                pastYear = year;
            }
                RiimRiskImportVO riskImport = new RiimRiskImportVO();
                riskImport.setStatus("02");
                riskImport.setAcctYear(year);
                riskImport.setManageCompCode(manageCompCode);
                //找到年度重点风险，然后生成披露报告
                List<RiimRiskImport> importList = riskImportMapper.selectList(riskImport);

                //接待办
                FltdTaskVO taskVO = new FltdTaskVO();
                String flowNo = "";
                if (CollectionUtils.isNotEmpty(importList)) {
                    for (RiimRiskImport riimRiskImport : importList) {
                        if("BGTA".equals(riimRiskImport.getManageCompCode())){
                            flowNo="fengxianpilubaogao";
                            taskVO.setFlowNo(flowNo);
                            taskVO.setFlowName("重点风险披露报告");
                        }else{
                            flowNo = "jidifengxianpilubaogao";
                            taskVO.setFlowNo(flowNo);
                            taskVO.setFlowName("重点风险披露报告（基地）");
                        }

                        taskVO.setAcctYear(year);
                        taskVO.setQuarterCode(quarterCurrent.toString());
                        taskVO.setQuarterName(DateUtils.getQuarterName(quarterCurrent.toString()));
                        //生成披露报告
                        RireRiskWarningStatus warningStatus = new RireRiskWarningStatus();
                        warningStatus.setImportGuid(riimRiskImport.getId());
                        warningStatus.setAcctYear(year);
                        warningStatus.setQuarterCode("" + quarterCurrent);
                        warningStatus.setEditPerson(riimRiskImport.getDutyUserName());
                        warningStatus.setRowOrder(riimRiskImport.getRowOrder());
                        warningStatus.setStrategy(riimRiskImport.getRemark());
                        warningStatus.setWaringStatus("");//为了首页展示数据
                        warningStatus.setNextWaringStatus("");//为了首页展示数据
                        List<RiskWarningStatusVO> statusList = rireRiskWarningStatusMapper.selectList(warningStatus, null);
                        //根据年度、季度、重点风险ID 找披露报告,如果找到，表示已经下发过，不再下发
                        //如果存在披露报告，但是没有待办，直接发起流程不添加披露报告记录
                        boolean flag = false;
                        if (CollectionUtils.isNotEmpty(statusList)) {
                            RireRiskWarningStatus report = statusList.get(0);
                            FltdTask task = new FltdTask();
                            task.setFlowNo(flowNo);
                            task.setAcctYear(riimRiskImport.getAcctYear());
                            task.setQuarterCode(quarterCurrent.toString());
                            task.setDeptCode(riimRiskImport.getDeptCode());
                            task.setTaskGuid(riimRiskImport.getId());
                            FltdTask fltdTask = fltdTaskService.selectExistTask(task);
                            if (fltdTask != null) {
                                continue;
                            } else {
                                flag = true;
                            }
                        }
                        if (!flag) {
                            warningStatus.setQuarterName(DateUtils.getQuarterName(quarterCurrent.toString()));
                            warningStatus.setRiskId(riimRiskImport.getRiskId());

                            warningStatus.setStatus("A01");
                            warningStatus.setStatusName("待填报");
                            warningStatus.setManageCompCode(riimRiskImport.getManageCompCode());
                            warningStatus.setManageCompName(riimRiskImport.getManageCompName());
                            warningStatus = (RireRiskWarningStatus) BeanUtils.initBean(warningStatus);
                            rireRiskWarningStatusMapper.insert(warningStatus);
                            // 将上一季度披露报告的风险指标和预警模型带到本季度
                            List<RiimRiskImport> riimRiskImportList = riskImportMapper.selectCheck(riimRiskImport.getRiskNo(), "", pastYear);
                            if (CollectionUtils.isNotEmpty(riimRiskImportList)) {
                                RiimRiskImport pastRiimRiskImport = riimRiskImportList.get(0);
//                            warningStatus.setImportGuid(pastRiimRiskImport.getId());
                                insertData(warningStatus, pastRiimRiskImport);
                            }
                            taskVO.setBizGuid(warningStatus.getId());
                        } else {
                            RireRiskWarningStatus report = statusList.get(0);
                            taskVO.setBizGuid(report.getId());
                        }

                        //填充工作流需要的数据
                        XtzyCompany company = new XtzyCompany();
                        company.setCompCode(riimRiskImport.getDeptCode());
                        company.setCompName(riimRiskImport.getDeptName());
                        taskVO.setCustomCompany(company);
                        taskVO.setCompCode(riimRiskImport.getCompCode());
                        taskVO.setCompName(riimRiskImport.getCompName());
                        taskVO.setDeptCode(riimRiskImport.getDeptCode());
                        taskVO.setDeptName(riimRiskImport.getDeptName());
                        String bizDesc = taskVO.getAcctYear() + "年度-" + taskVO.getQuarterName() + "-<" + riimRiskImport.getRiskName() + ">-重点风险披露报告";
                        taskVO.setBizName(bizDesc);
                        taskVO.setBizDesc(bizDesc);
                        taskVO.setTaskGuid(riimRiskImport.getId());
                        taskVO.setManageCompCode(riimRiskImport.getManageCompCode());
                        taskVO.setManageCompName(riimRiskImport.getManageCompName());
                        taskVO.setGroupCondition(taskVO.getAcctYear() + taskVO.getQuarterCode());
                        try {
                            startNum++;
                            //启动流程
                            fltdProcessService.doStart(taskVO);
                            logs.add(fltdProcessService.getLog("重点风险披露报告-流程启动成功", 0, "业务id：" + warningStatus.getId() + "，重点风险id：" + riimRiskImport.getId(), jobId));
                        } catch (Exception e) {
                            logs.add(fltdProcessService.getLog("重点风险披露报告-流程启动失败", 1, e.getMessage(), jobId));
                            error = e;
                            break;
                        }
                    }
                }

            //找到当年所有重点风险

            if (startNum == 0) {
                logs.add(fltdProcessService.getLog("重点风险披露报告-流程启动成功", 1, "未查到可以下发的重点风险数据", jobId));
            }
        } catch (Exception e) {
            logs.add(fltdProcessService.getLog("重点风险披露报告-下发失败", 1, e.getMessage(), jobId));
            error = e;
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }
        return true;
    }

    /**
     * 在生成复制披露报告的时候
     * 查看原披露报告是否存在重点风险的风险指标和预警模型，
     * 存在就将数据带到本季度
     *
     * @param newWarningStatus
     */
    private void insertData(RireRiskWarningStatus newWarningStatus,RireRiskWarningStatus oldWarningStatus) {
        RireRiskWarningStatus warningStatus = new RireRiskWarningStatus();
        warningStatus.setImportGuid(oldWarningStatus.getImportGuid());
        warningStatus.setAcctYear(oldWarningStatus.getAcctYear());
        warningStatus.setQuarterCode(oldWarningStatus.getQuarterCode());
        List<RiskWarningStatusVO> statusList = rireRiskWarningStatusMapper.selectList(warningStatus, null);
        if (CollectionUtils.isNotEmpty(statusList)) {
            for (RireRiskWarningStatus status : statusList) {
                insertTarget(status.getId(), newWarningStatus);
                insertWarning(status.getId(), newWarningStatus);
            }
        }

    }

    /**
     * 复制披露报告
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public List<RireRiskWarningStatus> copyImportByRisk(List<String> ids, String year,String quarter)throws Exception {
        List<RiimRiskImport> riskImportList = new ArrayList<>();
        for (String id:ids){
            RiimRiskImport riskImport = new RiimRiskImport();
            riskImport.setId(id);
            List<RiimRiskImport> select = riskImportMapper.select(riskImport);
            riskImportList.add(select.get(0));
        }
        List<RireRiskWarningStatus> list = new ArrayList<RireRiskWarningStatus>();
//        String year = (String) map.get("year");
//        String quarter = (String) map.get("quarter");
        String pastYear = "";
        if ("1".equals(quarter)) {
            pastYear = String.valueOf(Integer.valueOf(year) - 1);
        } else {
            pastYear = year;
        }

        for (RiimRiskImport riskImport : riskImportList){
            //先判断目标年份是否有这个 相关重点风险
            riskImport.setAcctYear(year);
            //现根据字段去查询历年风险Riririsk
            RiriRisk ririRisk = new RiriRisk();
            ririRisk.setAcctYear(year);
            ririRisk.setRiskNo(riskImport.getRiskNo());

            List<RiriRisk> select = ririRiskMapper.select(ririRisk);
            if (select.isEmpty()){
                throw new Exception(year+quarter+"风险自评不存在");
            }

            RiimRiskImport riskImport1 = new RiimRiskImport();
            riskImport1.setAcctYear(year);
            riskImport1.setRiskNo(riskImport.getRiskNo());
            List<RiimRiskImport> select1 = riskImportMapper.select(riskImport1);

            //如果没有就把原数据的重点风险 新增到目标年
            if (select1.isEmpty()){
                RiriRisk ririRisk1 = select.get(0);
                insertImportByRisk(ririRisk1);
                //然后再生成披露报告
                RireRiskWarningStatus rireRiskWarningStatus = copyTask(riskImport, year, quarter, pastYear);
                list.add(rireRiskWarningStatus);
            }else {
                //如果有直接生成披露报告
                RireRiskWarningStatus rireRiskWarningStatus = copyTask(riskImport, year, quarter, pastYear);
                list.add(rireRiskWarningStatus);
            }
        }

        return list;
    }

    public RireRiskWarningStatus copyTask(RiimRiskImport riskImport,String year,String quarter,String pastYear) throws Exception {
        RireRiskWarningStatus warningStatus = new RireRiskWarningStatus();
        warningStatus.setImportGuid(riskImport.getId());
        warningStatus.setAcctYear(year);
        warningStatus.setQuarterCode("Q" + quarter);
        warningStatus.setEditPerson(riskImport.getDutyUserName());
        warningStatus.setRowOrder(riskImport.getRowOrder());
        warningStatus.setStrategy(riskImport.getRemark());
        warningStatus.setWaringStatus("");//为了首页展示数据
        warningStatus.setNextWaringStatus("");//为了首页展示数据

        warningStatus.setQuarterName(DateUtils.getQuarterName(quarter));
        warningStatus.setRiskId(riskImport.getRiskId());
        warningStatus.setStatus("A01");
        warningStatus.setStatusName("待填报");
        warningStatus.setManageCompCode(riskImport.getManageCompCode());
        warningStatus.setManageCompName(riskImport.getManageCompName());
        warningStatus = (RireRiskWarningStatus) BeanUtils.initBean(warningStatus);
        rireRiskWarningStatusMapper.insert(warningStatus);
        // 将上一季度披露报告的风险指标和预警模型带到本季度
        List<RiimRiskImport> riimRiskImportList = riskImportMapper.selectCheck(riskImport.getRiskNo(), "", pastYear);
        if (CollectionUtils.isNotEmpty(riimRiskImportList)) {
            RiimRiskImport pastRiimRiskImport = riimRiskImportList.get(0);
//                            warningStatus.setImportGuid(pastRiimRiskImport.getId());
            insertData(warningStatus, pastRiimRiskImport);
        }else {
            throw new Exception("上季度数据不存在");
        }
        return warningStatus;
    }

    /**
     * 复制并下发
     * @param
     * @param ids
     * @throws Exception
     */
    @Override
    public Boolean copyAndIssue(List<String> ids, String year, String quarter) throws Exception {
        //List<RiimRiskImport> riskImportList = (List<RiimRiskImport>) map.get("list");
//        String year = (String) map.get("year");
//        String quarter = (String) map.get("quarter");
        List<RiimRiskImport> riskImportList = new ArrayList<>();
        for (String id:ids){
            RiimRiskImport riskImport = new RiimRiskImport();
            riskImport.setId(id);
            List<RiimRiskImport> select = riskImportMapper.select(riskImport);
            riskImportList.add(select.get(0));
        }

        String pastYear = "";
        if ("1".equals(quarter)) {
            pastYear = String.valueOf(Integer.valueOf(year) - 1);
        } else {
            pastYear = year;
        }

        //先复制  再下发
        List<RireRiskWarningStatus> riimRiskImports = copyImportByRisk(ids,year,quarter);

        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        int startNum = 0;
        try {

            //找到当年所有重点风险
            RiimRiskImportVO riskImport = new RiimRiskImportVO();
            riskImport.setStatus("02");
            riskImport.setAcctYear(year);
            //找到年度重点风险，然后生成披露报告
            List<RiimRiskImport> importList = riskImportMapper.selectList(riskImport);

            //接待办
            FltdTaskVO taskVO = new FltdTaskVO();
            String flowNo = "fengxianpilubaogao";
            taskVO.setFlowNo(flowNo);
            taskVO.setFlowName("重点风险披露报告");
            taskVO.setAcctYear(year);
            taskVO.setQuarterCode(quarter);
            taskVO.setQuarterName(DateUtils.getQuarterName(quarter));
            if (CollectionUtils.isNotEmpty(importList)) {
                for (RiimRiskImport riimRiskImport : importList) {
                    //生成披露报告
                    RireRiskWarningStatus warningStatus = new RireRiskWarningStatus();
                    warningStatus.setImportGuid(riimRiskImport.getId());
                    warningStatus.setAcctYear(year);
                    warningStatus.setQuarterCode(quarter);
                    warningStatus.setEditPerson(riimRiskImport.getDutyUserName());
                    warningStatus.setRowOrder(riimRiskImport.getRowOrder());
                    warningStatus.setStrategy(riimRiskImport.getRemark());
                    warningStatus.setWaringStatus("");//为了首页展示数据
                    warningStatus.setNextWaringStatus("");//为了首页展示数据
                    List<RiskWarningStatusVO> statusList = rireRiskWarningStatusMapper.selectList(warningStatus, null);
                    //根据年度、季度、重点风险ID 找披露报告,如果找到，表示已经下发过，不再下发
                    //如果存在披露报告，但是没有待办，直接发起流程不添加披露报告记录
                    boolean flag = false;
                    if (CollectionUtils.isNotEmpty(statusList)) {
                        RireRiskWarningStatus report = statusList.get(0);
                        FltdTask task = new FltdTask();
                        task.setFlowNo(flowNo);
                        task.setAcctYear(riimRiskImport.getAcctYear());
                        task.setQuarterCode(quarter);
                        task.setDeptCode(riimRiskImport.getDeptCode());
                        task.setTaskGuid(riimRiskImport.getId());
                        FltdTask fltdTask = fltdTaskService.selectExistTask(task);
                        if (fltdTask != null) {
                            continue;
                        } else {
                            flag = true;
                        }
                    }
                    if (!flag) {
                        warningStatus.setQuarterName(DateUtils.getQuarterName(quarter));
                        warningStatus.setRiskId(riimRiskImport.getRiskId());

                        warningStatus.setStatus("A01");
                        warningStatus.setStatusName("待填报");
                        warningStatus.setManageCompCode(riimRiskImport.getManageCompCode());
                        warningStatus.setManageCompName(riimRiskImport.getManageCompName());
                        warningStatus = (RireRiskWarningStatus) BeanUtils.initBean(warningStatus);

                        //因为复制功能是要把指定日期的上个季度的披露报告拿来做复制,如果上个季度的披露报告不存在那就抛异常
                        List<RiimRiskImport> riimRiskImportList = riskImportMapper.selectCheck(riimRiskImport.getRiskNo(), "", pastYear);
                        if (riimRiskImportList.size() == 0){
                            throw new Exception("指定日期上季度披露报告不存在");
                        }

                        rireRiskWarningStatusMapper.insert(warningStatus);
                        // 将上一季度披露报告的风险指标和预警模型带到本季度
//                        List<RiimRiskImport> riimRiskImportList = riskImportMapper.selectCheck(riimRiskImport.getRiskNo(), "", pastYear);
//                        if (riimRiskImportList.size() == 0){
//                            throw new Exception("指定日期上季度披露报告不存在");
//                        }
                        if (CollectionUtils.isNotEmpty(riimRiskImportList)) {
                            RiimRiskImport pastRiimRiskImport = riimRiskImportList.get(0);
//                            warningStatus.setImportGuid(pastRiimRiskImport.getId());
                            insertData(warningStatus, pastRiimRiskImport);
                        }
                        taskVO.setBizGuid(warningStatus.getId());
                    } else {
                        RireRiskWarningStatus report = statusList.get(0);
                        taskVO.setBizGuid(report.getId());
                    }

                    //填充工作流需要的数据
                    XtzyCompany company = new XtzyCompany();
                    company.setCompCode(riimRiskImport.getDeptCode());
                    company.setCompName(riimRiskImport.getDeptName());
                    taskVO.setCustomCompany(company);
                    taskVO.setCompCode(riimRiskImport.getCompCode());
                    taskVO.setCompName(riimRiskImport.getCompName());
                    taskVO.setDeptCode(riimRiskImport.getDeptCode());
                    taskVO.setDeptName(riimRiskImport.getDeptName());
                    String bizDesc = taskVO.getAcctYear() + "年度-" + taskVO.getQuarterName() + "-<" + riimRiskImport.getRiskName() + ">-重点风险披露报告";
                    taskVO.setBizName(bizDesc);
                    taskVO.setBizDesc(bizDesc);
                    taskVO.setTaskGuid(riimRiskImport.getId());
                    taskVO.setManageCompCode(riimRiskImport.getManageCompCode());
                    taskVO.setManageCompName(riimRiskImport.getManageCompName());
                    taskVO.setGroupCondition(taskVO.getAcctYear() + taskVO.getQuarterCode());
                    try {
                        startNum++;
                        //启动流程
                        fltdProcessService.doStart(taskVO);
                    } catch (Exception e) {
                        error = e;
                        break;
                    }
                }
            }
            if (startNum == 0) {
                System.out.println("成功!");
            }
        } catch (Exception e) {
            logs.add(fltdProcessService.getLog("重点风险披露报告-下发失败", 1, e.getMessage(), "失败"));
            error = e;
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }
        return true;
    }

    /**
     * 在生成披露报告的时候
     * 查看上一季度的披露报告是否存在重点风险的风险指标和预警模型，
     * 存在就将数据带到本季度
     *
     * @param newWarningStatus
     */
    private void insertData(RireRiskWarningStatus newWarningStatus, RiimRiskImport pastRiimRiskImport) {
        String acctYear;
        String quarterCode;
        if (1 == Integer.valueOf(newWarningStatus.getQuarterCode())) {
            quarterCode = "4";
            acctYear = String.valueOf(Integer.valueOf(newWarningStatus.getAcctYear()) - 1);
        } else {
            quarterCode = String.valueOf(Integer.valueOf(newWarningStatus.getQuarterCode()) - 1);
            acctYear = newWarningStatus.getAcctYear();
        }

        RireRiskWarningStatus warningStatus = new RireRiskWarningStatus();
        warningStatus.setImportGuid(pastRiimRiskImport.getId());
        warningStatus.setAcctYear(acctYear);
        warningStatus.setQuarterCode(quarterCode);
        List<RiskWarningStatusVO> statusList = rireRiskWarningStatusMapper.selectList(warningStatus, null);
        if (CollectionUtils.isNotEmpty(statusList)) {
            for (RireRiskWarningStatus status : statusList) {
                insertTarget(status.getId(), newWarningStatus);
                insertWarning(status.getId(), newWarningStatus);
            }
        }

    }

    /**
     * 根据上一季度的披露报告查询重点风险指标，
     * 如果存在就带到本季度
     *
     * @param lastReportGuid
     * @param newWarningStatus
     */
    private void insertTarget(String lastReportGuid, RireRiskWarningStatus newWarningStatus) {
        List<RireRiskTarget> targetList = rireRiskTargetMapper.getTargetByImportId(lastReportGuid);
        if (CollectionUtils.isNotEmpty(targetList)) {
            for (RireRiskTarget target : targetList) {
                target = (RireRiskTarget) BeanUtils.initBean(target);
                target.setImportGuid(newWarningStatus.getImportGuid());
                target.setRiskId(newWarningStatus.getRiskId());
                target.setImportReportGuid(newWarningStatus.getId());
                target.setQuarterCode(newWarningStatus.getQuarterCode());
                target.setQuarterName(newWarningStatus.getQuarterName());
                target.setManageCompCode(newWarningStatus.getManageCompCode());
                target.setManageCompName(newWarningStatus.getManageCompName());
                rireRiskTargetMapper.insert(target);
            }
        }
    }

    /**
     * 根据上一季度的披露报告查询预警模型
     * 如果存在就带到本季度
     * 预警模型 =》 预警状态 =》 预警规则 =》预警指标
     *
     * @param lastReportGuid
     * @param newWarningStatus
     */
    private void insertWarning(String lastReportGuid, RireRiskWarningStatus newWarningStatus) {
        // 预警模型
        List<RiwaRiskWaring> waringList = riskWaringMapper.getWaringByImportId(lastReportGuid);
        if (CollectionUtils.isNotEmpty(waringList)) {
            for (RiwaRiskWaring waring : waringList) {
                // 预警模型状态
                List<RiwaRiskWaringStatus> waringStatusList = riskWaringStatusMapper.getWaringStatusByWaringId(waring.getId());
                waring = (RiwaRiskWaring) BeanUtils.initBean(waring);
                waring.setImportGuid(newWarningStatus.getImportGuid());
                waring.setRiskId(newWarningStatus.getRiskId());
                waring.setImportReportGuid(newWarningStatus.getId());
                waring.setAcctYear(newWarningStatus.getAcctYear());
                waring.setQuarterCode(newWarningStatus.getQuarterCode());
                waring.setQuarterName(newWarningStatus.getQuarterName());
                waring.setManageCompCode(newWarningStatus.getManageCompCode());
                waring.setManageCompName(newWarningStatus.getManageCompName());
                riskWaringMapper.insert(waring);
                if (CollectionUtils.isNotEmpty(waringStatusList)) {
                    for (RiwaRiskWaringStatus waringStatus : waringStatusList) {
                        // 预警规则
                        List<RiwaRiskWaringRule> waringRuleList = riskWaringRuleMapper.getWaringRuleByStatusId(waringStatus.getId());
                        waringStatus = (RiwaRiskWaringStatus) BeanUtils.initBean(waringStatus);
                        waringStatus.setWarningModelGuid(waring.getId());
                        waringStatus.setImportGuid(newWarningStatus.getId());
                        waringStatus.setRiskId(newWarningStatus.getRiskId());
                        riskWaringStatusMapper.insert(waringStatus);
                        if (CollectionUtils.isNotEmpty(waringRuleList)) {
                            for (RiwaRiskWaringRule waringRule : waringRuleList) {
                                // 预警指标
                                List<RiwaRiskWaringTarget> waringTargetList = riskWaringTatgetMapper.getWaringTargetByRuleId(waringRule.getId());
                                waringRule = (RiwaRiskWaringRule) BeanUtils.initBean(waringRule);
                                waringRule.setImportGuid(newWarningStatus.getId());
                                waringRule.setRiskId(newWarningStatus.getRiskId());
                                waringRule.setWaringStatusGuid(waringStatus.getId());
                                waringRule.setWarningModelGuid(waring.getId());
                                riskWaringRuleMapper.insert(waringRule);
                                if (CollectionUtils.isNotEmpty(waringTargetList)) {
                                    for (RiwaRiskWaringTarget waringTarget : waringTargetList) {
                                        waringTarget = (RiwaRiskWaringTarget) BeanUtils.initBean(waringTarget);
                                        waringTarget.setWarningRuleId(waringRule.getId());
                                        waringTarget.setImportGuid(newWarningStatus.getId());
                                        waringTarget.setRiskId(newWarningStatus.getRiskId());
                                        waringTarget.setWarningModelGuid(waring.getId());
                                        waringTarget.setWaringStatusGuid(waringStatus.getId());
                                        riskWaringTatgetMapper.insert(waringTarget);
                                    }
                                }
                            }
                        }

                    }
                }

            }
        }
    }

    /**
     * 重点风险业务数据下发待办balabala
     */
    private void savePone(List<RiimRiskImport> importList) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        try {
            if (CollectionUtils.isEmpty(importList)) {
                log.error("当季度没有重点风险，无法执行下发操作！");
                throw new Exception("当季度没有重点风险，无法执行下发操作！");
            }
            FltdTaskVO taskVO = new FltdTaskVO();
            taskVO.setFlowName("重点风险实施方案");
            for (RiimRiskImport anImport : importList) {
            	String manageCompCode = anImport.getManageCompCode();
            	if("BGTA".equals(manageCompCode)){
            		taskVO.setFlowNo("fengxianshishifangan");
            	}else{
            		taskVO.setFlowNo("jidishishifangan");
            	}

                //如果存在实施方案，但是没有待办，直接发起流程
                if (StringUtils.isNotEmpty(anImport.getPlanStatus())) {
                    FltdTask task = new FltdTask();
                    task.setFlowNo(taskVO.getFlowNo());
                    task.setAcctYear(anImport.getAcctYear());
                    task.setDeptCode(anImport.getDeptCode());
                    task.setTaskGuid(anImport.getId());
                    FltdTask fltdTask = fltdTaskService.selectExistTask(task);
                    if (fltdTask != null) {
                        continue;
                    }
                }

                XtzyCompany company = new XtzyCompany();
                company.setCompCode(anImport.getDeptCode());
                company.setCompName(anImport.getDeptName());
                taskVO.setCustomCompany(company);
                taskVO.setTaskGuid(anImport.getId());
                taskVO.setBizGuid(anImport.getId());
                taskVO.setCompCode(anImport.getCompCode());
                taskVO.setCompName(anImport.getCompName());
                taskVO.setDeptCode(anImport.getDeptCode());
                taskVO.setDeptName(anImport.getDeptName());
                taskVO.setManageCompCode(anImport.getManageCompCode());
                taskVO.setManageCompName(anImport.getManageCompName());
                // 年度取重点风险，不再取当前年度
                taskVO.setAcctYear(anImport.getAcctYear());
                String bizName = anImport.getManageCompName() + taskVO.getAcctYear() + "年度，重点风险实施方案：" + anImport.getRiskName();
                taskVO.setBizName(bizName);
                String bizDesc = taskVO.getAcctYear() + "年度<" + anImport.getRiskName() + ">重点风险实施方案";
                taskVO.setBizDesc(bizDesc);
                taskVO.setGroupCondition(taskVO.getAcctYear());
                try {
                    //启动流程
                    fltdProcessService.doStart(taskVO);
                    logs.add(fltdProcessService.getLog("重点风险实施方案-流程启动成功", 0, "业务id：" + anImport.getId() + "，重点风险id：" + anImport.getId(), null));
                } catch (Exception e) {
                    logs.add(fltdProcessService.getLog("重点风险实施方案-流程启动失败", 1, e.getMessage(), null));
                    error = e;
                    break;
                }

                RiimRiskImport riskImport = new RiimRiskImport();
                riskImport = (RiimRiskImport) BeanUtils.updateBean(riskImport);
                riskImport.setPlanStatus("A01");
                riskImport.setPlanStatusName("待分配");
                riskImport.setId(anImport.getId());
                update(riskImport);
            }
        } catch (Exception e) {
            logs.add(fltdProcessService.getLog("重点风险实施方案-下发异常", 1, e.getMessage(), null));
            error = e;
        }
        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }

    }

    /**
     * 重点风险结题下发待办
     */
    public void saveConclusion(List<RiimRiskImport> importList) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        if (importList.isEmpty()) {
            log.error("选择数据为空");
            throw new Exception("选择数据为空,无法进行下发待办操作");
        }
        FltdTaskVO taskVO = new FltdTaskVO();
        for (RiimRiskImport anImport : importList){
            //获取风险结题申请
            RifiFinishVO finishTask = finishService.getFinishByImportId(anImport);
            finishService.saveRifiFinish(finishTask); //批量保存更新风险结题申请
            //复制能力测评相关数据
            RifiRiskFinish finishParam=new RifiRiskFinish();
            BeanUtils.copyBeanProp(finishParam, finishTask.getRifiRiskFinish());
            finishService.doIssuedEvaluate(finishParam);
            if("BGTA".equals(anImport.getManageCompCode())){
                taskVO.setFlowNo("fengxianjieti");
                taskVO.setFlowName("重点风险结题");
            }else{
                taskVO.setFlowNo("jidijieticeping");
                taskVO.setFlowName("基地重点风险结题");
            }
        }



        for (RiimRiskImport anImport : importList) {
            //如果存在实施方案，但是没有待办，直接发起流程
            if (StringUtils.isNotEmpty(anImport.getPlanStatus())) {
                FltdTask task = new FltdTask();
                task.setFlowNo(taskVO.getFlowNo());
                task.setAcctYear(anImport.getAcctYear());
                task.setDeptCode(anImport.getDeptCode());
                task.setTaskGuid(anImport.getId());
                FltdTask fltdTask = fltdTaskService.selectExistTask(task);
                if (fltdTask != null) {
                    continue;
                }
            }

            //更改风险结题页面查询结果
            anImport.setConclusionStatus("Y");

            riskImportMapper.updateConclusionStatusById(anImport);

            finishService.doSubmit(anImport);

        }


        // 保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }

    }

    @Override
    public Integer updateImportList(List<RiimRiskImport> riskImportList) {
        for (RiimRiskImport riskImport : riskImportList) {
            riskImportMapper.updateByPrimaryKeySelective(riskImport);
        }
        return 1;
    }


    @Override
    public Integer deleteImport(List<String> ids) throws Exception {
        for (String id : ids) {
            RiimRiskImport riskImport = riskImportMapper.selectByPrimaryKey(id);
            if (!"01".equals(riskImport.getStatus())) {
                log.error("状态非【草稿】，不可以删除！");
                throw new Exception("状态非【草稿】，不可以删除！");
            }
            if (StringUtils.isNotEmpty(riskImport.getPlanStatus())) {
                log.error("已经存在实施方案,不可以删除！");
                throw new Exception("已经存在实施方案，不可以删除！");
            }
            //如果历史ID为空，表示新加的，可以直接删除
            if (StringUtils.isNotEmpty(riskImport.getRiskNoHis())) {
                riskImportMapper.updateStatus(id, "09", "关闭");
            } else {
                riskImportMapper.deleteByPrimaryKey(id);
            }
        }
        return 1;
    }

    @Override
    public Integer updateStatus(String id, String status, String statusName) {
        return riskImportMapper.updateStatus(id, status, statusName);
    }

    @Override
    public Integer updateImport(RiimRiskImportVO importVO) throws Exception {
        Integer row = riskImportMapper.updateByPrimaryKeySelective(importVO);
        //实施方案修改的时候，一起修改风险自评的风险描述和风险库
        RiriRisk ririRisk = ririRiskMapper.selectByPrimaryKey(importVO.getRiskId());
        if (ririRisk != null) {
            RiriRisk risk = new RiriRisk();
            risk.setId(importVO.getRiskId());
            risk.setRiskDesc(importVO.getRiskDesc());
            ririRiskMapper.updateByPrimaryKeySelective(risk);
        }
        //修改风险库
//        if (StringUtils.isNotEmpty(ririRisk.getRiaaRiskNo())){
//            RiaaRiskVO riaaRisk = new RiaaRiskVO();
//            riaaRisk.setRiskNo(ririRisk.getRiaaRiskNo());
//            List<RiaaRisk> riaaRiskList = riaaRiskMapper.selectRiaaRisk(riaaRisk);
//            if (CollectionUtils.isNotEmpty(riaaRiskList)){
//                for (RiaaRisk risk : riaaRiskList) {
//                    risk.setRiskDesc(importVO.getRiskDesc());
//                    riaaRiskMapper.updateByPrimaryKeySelective(risk);
//                }
//            }
//        }
        //添加主要职责及分工
        if (!CollectionUtils.isEmpty(importVO.getAssignmentList())) {
            //先删除，后新增
            assignmentMapper.deleteByImportGuid(importVO.getId());
            for (RiimRiskAssignment assignment : importVO.getAssignmentList()) {
                assignment = (RiimRiskAssignment) BeanUtils.initBean(assignment);
                assignment.setImportGuid(importVO.getId());
                Integer rowOrder;
                Integer maxRowOrder = assignmentMapper.queryMax(assignment.getImportGuid());
                if (maxRowOrder == null) {
                    rowOrder = 1;
                } else {
                    rowOrder = maxRowOrder + 1;
                }
                assignment.setRowOrder(rowOrder);
                assignmentMapper.insert(assignment);
            }
        }
        //添加人员---先删除，后新增
        dutyUserMapper.deleteByGuidAndType(importVO.getId(), dutyLead);
        dutyUserMapper.deleteByGuidAndType(importVO.getId(), exeLead);
        if (CollectionUtils.isNotEmpty(importVO.getDutyUserList())) {
            for (RiriDutyUser ririDutyUser : importVO.getDutyUserList()) {
                ririDutyUser.setBizGuid(importVO.getId());
                ririDutyUser = (RiriDutyUser) BeanUtils.initBean(ririDutyUser);
                dutyUserMapper.insert(ririDutyUser);
            }
        }
        //添加单位---先删除，后新增
        dutyCompMapper.deleteByGuidAndType(importVO.getId(), dutyComp);
        dutyCompMapper.deleteByGuidAndType(importVO.getId(), auxiliaryComp);
        if (CollectionUtils.isNotEmpty(importVO.getDutyCompList())) {
            for (RiriDutyComp ririDutyComp : importVO.getDutyCompList()) {
                ririDutyComp.setBizGuid(importVO.getId());
                ririDutyComp = (RiriDutyComp) BeanUtils.initBean(ririDutyComp);
                dutyCompMapper.insert(ririDutyComp);
            }
        }
        //添加风险评估
        if (!CollectionUtils.isEmpty(importVO.getEvaluationList())) {
            //先删除，后新增
            evaluationMapper.deleteByImportGuid(importVO.getId());
            for (RiimRiskEvaluation evaluation : importVO.getEvaluationList()) {
                evaluation = (RiimRiskEvaluation) BeanUtils.initBean(evaluation);
                evaluation.setImportGuid(importVO.getId());
                Integer rowOrder;
                Integer maxRowOrder = evaluationMapper.queryMax(evaluation.getImportGuid());
                if (maxRowOrder == null) {
                    rowOrder = 1;
                } else {
                    rowOrder = maxRowOrder + 1;
                }
                evaluation.setRowOrder(rowOrder);
                evaluationMapper.insert(evaluation);
            }
        }
        //添加项目目标及明细
        if (!CollectionUtils.isEmpty(importVO.getGoalList())) {
            //先删除，后新增
            List<RiimRiskGoal> goalList = goalMapper.selectByImportGuid(importVO.getId());
            if (!CollectionUtils.isEmpty(goalList)) {
                for (RiimRiskGoal goal : goalList) {
                    goalDetailtMapper.deleteByImportGuidAndGoalId(importVO.getId(), goal.getId());
                }
            }
            goalMapper.deleteByImportGuid(importVO.getId());
            //新增项目目标
            for (RiimRiskGoalVO goalVO : importVO.getGoalList()) {
                if (StringUtils.isEmpty(goalVO.getGoalYear())) {
                    throw new Exception("项目目标的年度目标不能为空");
                }
                goalVO = (RiimRiskGoalVO) BeanUtils.initBean(goalVO);
                goalVO.setImportGuid(importVO.getId());
                if ("B".equals(goalVO.getQuantityFlag())) {
                    if (StringUtils.isEmpty(goalVO.getGoalFirst())) {
                        goalVO.setGoalFirst(goalVO.getGoalYear());
                    }
                    if (StringUtils.isEmpty(goalVO.getGoalSecond())) {
                        goalVO.setGoalSecond(goalVO.getGoalYear());
                    }
                    if (StringUtils.isEmpty(goalVO.getGoalThird())) {
                        goalVO.setGoalThird(goalVO.getGoalYear());
                    }
                    if (StringUtils.isEmpty(goalVO.getGoalFour())) {
                        goalVO.setGoalFour(goalVO.getGoalYear());
                    }
                }
                Integer rowOrder;
                Integer maxRowOrder = goalMapper.queryMax(goalVO.getImportGuid());
                if (maxRowOrder == null) {
                    rowOrder = 1;
                } else {
                    rowOrder = maxRowOrder + 1;
                }
                goalVO.setRowOrder(rowOrder);
                goalMapper.insert(goalVO);
                //新增项目目标-明细表
                if (!CollectionUtils.isEmpty(goalVO.getGoalDetailList())) {
                    insertDetail(goalVO.getGoalDetailList(), goalVO.getId(), importVO.getId(), null);
                    if ("A".equals(goalVO.getQuantityFlag())) {
                        Map<String, List<RiimRiskGoalDetail>> map = goalVO.getGoalDetailList().stream().collect(Collectors.groupingBy(b -> b.getTypeFlag()));
                        List<RiimRiskGoalDetail> detailList = map.get("0");
                        if (CollectionUtils.isNotEmpty(detailList)) {
                            if (StringUtils.isEmpty(goalVO.getGoalFirst())) {
                                insertDetail(detailList, goalVO.getId(), importVO.getId(), "1");
                                goalVO.setGoalFirst(goalVO.getGoalYear());
                            }
                            if (StringUtils.isEmpty(goalVO.getGoalSecond())) {
                                insertDetail(detailList, goalVO.getId(), importVO.getId(), "2");
                                goalVO.setGoalSecond(goalVO.getGoalYear());
                            }
                            if (StringUtils.isEmpty(goalVO.getGoalThird())) {
                                insertDetail(detailList, goalVO.getId(), importVO.getId(), "3");
                                goalVO.setGoalThird(goalVO.getGoalYear());
                            }
                            if (StringUtils.isEmpty(goalVO.getGoalFour())) {
                                insertDetail(detailList, goalVO.getId(), importVO.getId(), "4");
                                goalVO.setGoalFour(goalVO.getGoalYear());
                            }
                            goalMapper.updateByPrimaryKeySelective(goalVO);
                        }
                    }
                }
            }

        }
        return row;
    }

    public void insertDetail(List<RiimRiskGoalDetail> detailList, String goalId, String importId, String typeFlag) {
        for (RiimRiskGoalDetail detail : detailList) {
            detail = (RiimRiskGoalDetail) BeanUtils.initBean(detail);
            detail.setGoalId(goalId);
            detail.setImportGuid(importId);
            if (StringUtils.isNotEmpty(typeFlag)) {
                detail.setTypeFlag(typeFlag);
            }
            goalDetailtMapper.insert(detail);
        }
    }


    @Override
    public RiimRiskImportVO getImport(String id) {
        RiimRiskImport riskImport = riskImportMapper.selectByPrimaryKey(id);
        RiimRiskImportVO importVO = new RiimRiskImportVO();
        BeanUtils.copyBeanProp(importVO, riskImport);
        List<RiimRiskAssignment> assignmentList = assignmentMapper.selectByImportGuid(id);
        if (!CollectionUtils.isEmpty(assignmentList)) {
            importVO.setAssignmentList(assignmentList);
        }
        List<RiimRiskEvaluation> evaluationList = evaluationMapper.selectByImportGuid(id);
        if (!CollectionUtils.isEmpty(evaluationList)) {
            importVO.setEvaluationList(evaluationList);
        }
        List<RiriDutyComp> dutyCompList = dutyCompMapper.selectByGuidAndType(id, dutyComp);
        dutyCompList.addAll(dutyCompMapper.selectByGuidAndType(id, auxiliaryComp));
        importVO.setDutyCompList(dutyCompList);

        List<RiriDutyUser> dutyUserList = dutyUserMapper.selectByGuidAndType(id, dutyLead);
        dutyUserList.addAll(dutyUserMapper.selectByGuidAndType(id, exeLead));
        importVO.setDutyUserList(dutyUserList);
        List<RiimRiskGoal> goalList = goalMapper.selectByImportGuid(id);
        if (!CollectionUtils.isEmpty(goalList)) {
            List<RiimRiskGoalVO> goalVOList = new ArrayList<>();
            for (RiimRiskGoal goal : goalList) {
                RiimRiskGoalVO goalVO = new RiimRiskGoalVO();
                BeanUtils.copyBeanProp(goalVO, goal);
                List<RiimRiskGoalDetail> goalDetailList = goalDetailtMapper.selectByImportGuidAndGoalId(id, goal.getId());
                if (!CollectionUtils.isEmpty(goalDetailList)) {
                    goalVO.setGoalDetailList(goalDetailList);
                }
                goalVOList.add(goalVO);

            }
            importVO.setGoalList(goalVOList);
        }
        return importVO;
    }


    @Override
    public List<RiimRiskGoalDetail> selectByType(String goalId, String typeFlag) {
        return goalDetailtMapper.selectByType(goalId, typeFlag);
    }

    /**
     * 导出汇总实施方案word数据
     *
     * @return
     */
    @Override
    public Map mainImportWord(List<String> importIds) {
        Map map = new HashMap<String, Object>();
        int index = 0;
        List<Map> list = new ArrayList<>();
        for (String importId : importIds) {
            Map map1 = importWord(importId);
            map1.put("size", index += 1);
            list.add(map1);
        }
        map.put("mainlist", list);
        return map;
    }

    /**
     * 组装导出word数据
     *
     * @param id
     * @return
     */
    @Override
    public Map importWord(String id) {
        RiimRiskImportVO importVo = getImport(id);
        if (null == importVo) {
            importVo = new RiimRiskImportVO();
        }
        Map map = new HashMap<String, Object>();
        //风险评估
        List<Map<String, Object>> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(importVo.getEvaluationList())) {
            Integer index = 0;
            for (RiimRiskEvaluation evaluation : importVo.getEvaluationList()) {
                index = index + 1;
                Map<String, Object> map1 = new HashMap<>();
                map1.put("index", index.toString());
                map1.put("name", (StringUtils.isEmpty(evaluation.getRiskName())) ? " " : evaluation.getRiskName());
                map1.put("desc", (StringUtils.isEmpty(evaluation.getStrategyName())) ? " " : evaluation.getStrategyName());
                list.add(map1);
            }
        } else {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("index", " ");
            map1.put("name", " ");
            map1.put("desc", " ");
            list.add(map1);
        }
        //项目目标
        List<Map<String, Object>> listA = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(importVo.getGoalList())) {
            for (RiimRiskGoalVO goalVO : importVo.getGoalList()) {
                Map<String, Object> map2 = new HashMap<>();
                map2.put("goalDesc", (StringUtils.isEmpty(goalVO.getGoalDesc())) ? " " : goalVO.getGoalDesc());
                map2.put("goalYear", (StringUtils.isEmpty(goalVO.getGoalYear())) ? " " : zhaunhuan(goalVO.getGoalYear()));
                map2.put("goalFirst", (StringUtils.isEmpty(goalVO.getGoalFirst())) ? " " : zhaunhuan(goalVO.getGoalFirst()));
                map2.put("goalSecond", (StringUtils.isEmpty(goalVO.getGoalSecond())) ? " " : zhaunhuan(goalVO.getGoalSecond()));
                map2.put("goalThird", (StringUtils.isEmpty(goalVO.getGoalThird())) ? " " : zhaunhuan(goalVO.getGoalThird()));
                map2.put("goalFour", (StringUtils.isEmpty(goalVO.getGoalFour())) ? " " : zhaunhuan(goalVO.getGoalFour()));
                listA.add(map2);
            }
        } else {
            Map<String, Object> map2 = new HashMap<>();
            map2.put("goalDesc", " ");
            map2.put("goalYear", " ");
            map2.put("goalFirst", " ");
            map2.put("goalSecond", " ");
            map2.put("goalThird", " ");
            map2.put("goalFour", " ");
            listA.add(map2);
        }
        //主要任务及职责分工
        List<Map<String, Object>> listB = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(importVo.getAssignmentList())) {
            for (RiimRiskAssignment assignment : importVo.getAssignmentList()) {
                Map<String, Object> map3 = new HashMap<>();
                map3.put("quarterName", (StringUtils.isEmpty(assignment.getQuarterName())) ? " " : assignment.getQuarterName());
                map3.put("taskName", (StringUtils.isEmpty(assignment.getTaskName())) ? " " : assignment.getTaskName());
                map3.put("dutyCompName", (StringUtils.isEmpty(assignment.getDutyCompName())) ? " " : assignment.getDutyCompName());
                String auxiliaryCompName = StringUtils.isEmpty(assignment.getAuxiliaryCompName()) ? " " : assignment.getAuxiliaryCompName();
                if (StringUtils.isNotEmpty(assignment.getAuxiliaryCompNameW())) {
                    auxiliaryCompName = auxiliaryCompName + "," + assignment.getAuxiliaryCompNameW();
                }
                map3.put("auxiliaryCompName", auxiliaryCompName);
                listB.add(map3);
            }
        } else {
            Map<String, Object> map3 = new HashMap<>();
            map3.put("quarterName", " ");
            map3.put("taskName", " ");
            map3.put("dutyCompName", " ");
            map3.put("auxiliaryCompName", " ");
            listB.add(map3);
        }
        String planBeginDate;
        String planEndDate;
        planBeginDate = (null == DateUtils.formatYYYYMMDD(importVo.getPlanBeginDate())) ? " " : DateUtils.formatYYYYMMDD(importVo.getPlanBeginDate());
        if (StringUtils.isNotEmpty(planBeginDate)) {
            StringBuilder sb = new StringBuilder(planBeginDate);
            planBeginDate = sb.insert(4, "年").insert(7, "月").insert(sb.length(), "日").toString();
        }
        planEndDate = (null == DateUtils.formatYYYYMMDD(importVo.getPlanEndDate())) ? " " : DateUtils.formatYYYYMMDD(importVo.getPlanEndDate());
        if (StringUtils.isNotEmpty(planEndDate)) {
            StringBuilder sb = new StringBuilder(planEndDate);
            planEndDate = sb.insert(4, "年").insert(7, "月").insert(sb.length(), "日").toString();
        }
        //重点风险
        map.put("acctYear", (StringUtils.isEmpty(importVo.getAcctYear())) ? " " : importVo.getAcctYear());
        map.put("riskName", (StringUtils.isEmpty(importVo.getRiskName())) ? " " : importVo.getRiskName());
        map.put("planBeginDate", planBeginDate);
        map.put("planEndDate", planEndDate);
        map.put("riskDesc", (StringUtils.isEmpty(importVo.getRiskDesc())) ? " " : importVo.getRiskDesc().replaceAll("\\s*",""));
//        map.put("planBeginDate", (null == DateUtils.formatYYYYMMDD(importVo.getPlanBeginDate())) ? " " : DateUtils.formatYYYYMMDD(importVo.getPlanBeginDate()));
//        map.put("planEndDate", (null == DateUtils.formatYYYYMMDD(importVo.getPlanEndDate())) ? " " : DateUtils.formatYYYYMMDD(importVo.getPlanEndDate()));
//        map.put("planBeginDate",DateUtils.formatYYYYMMDD(new Date()));
//        map.put("planEndDate",DateUtils.formatYYYYMMDD(new Date()));
        map.put("exeLeadName", (StringUtils.isEmpty(importVo.getExeLeadName())) ? " " : importVo.getExeLeadName());
        map.put("dutyCompName", (StringUtils.isEmpty(importVo.getDutyCompName())) ? " " : importVo.getDutyCompName());
        map.put("auxiliaryCompName", (StringUtils.isEmpty(importVo.getAuxiliaryCompName())) ? " " : importVo.getAuxiliaryCompName());
        map.put("dutyLeadName", (StringUtils.isEmpty(importVo.getDutyLeadName())) ? " " : importVo.getDutyLeadName());
        map.put("advanceMechanism", convertParam(importVo.getAdvanceMechanism(), advanceMechanismTemplate, "${advanceMechanism}"));
        map.put("trainNeed", convertParam(importVo.getTrainNeed(), trainNeedTemplate, "${trainNeed}"));
        map.put("dutyUserName", (StringUtils.isEmpty(importVo.getDutyUserName())) ? " " : importVo.getDutyUserName());
        map.put("date", DateUtils.format(new Date(), "yyyy年 MM月 dd日"));
        map.put("editorName", (StringUtils.isEmpty(importVo.getEditorName())) ? map.get("dutyUserName") : importVo.getEditorName());
        map.put("groupUserName",  (StringUtils.isEmpty(importVo.getExeLeadName())) ? " " : importVo.getExeLeadName());
        map.put("deptUserName", (StringUtils.isEmpty(importVo.getDeptUserName())) ? " " : importVo.getDeptUserName());

        map.put("list", list);
        map.put("listA", listA);
        map.put("listB", listB);
        return map;
    }

    @Override
    public void updateStatus(List<String> ids, String ext1, String ext2, String ext3, String ext4) {
        ids.forEach(id -> {
            RiimRiskImport riskImport = new RiimRiskImport();
            riskImport = (RiimRiskImport) BeanUtils.updateBean(riskImport);
            riskImport.setId(id);
            riskImport.setDutyUserCode(ext1);
            riskImport.setDutyUserName(ext2);
            riskImport.setExt8(ext3);
            riskImport.setExt9(ext4);
            update(riskImport);
        });

    }

    @Override
    public void saveImport(RiimRiskImport riimRiskImport) {
        riskImportMapper.updateByPrimaryKeySelective(riimRiskImport);
    }

    @Override
    public void updateRowOrder(RiimRiskImportVO riskImport, XtzyUser user) {
        if (StringUtils.isNotEmpty(riskImport.getAcctYear())) {
            riskImport.setAcctYear(riskImport.getAcctYear().substring(0, 4));
        }
        if (null != user) {
            riskImport.setCompIdList(riaaRiskService.getCompCodes(user.getExt1(), riskImport.getExt5()));
        }
        RiimRiskImport riskImport1 = get(riskImport.getId());
        List<String> ids = riskImportMapper.selectList(riskImport).stream().map(RiimRiskImport::getId).collect(Collectors.toList());
        ;
        int i = ids.indexOf(riskImport.getId());
        if ("up".equals(riskImport.getExt2())) {
            i--;
        } else {
            i++;
        }
        if (i < ids.size() && i >= 0) {
            RiimRiskImport riskImport2 = get(ids.get(i));
            Integer rowOrder1 = riskImport1.getRowOrder();
            Integer rowOrder2 = riskImport2.getRowOrder();
            riskImport2.setRowOrder(rowOrder1);
            update(riskImport2);
            riskImport1.setRowOrder(rowOrder2);
            update(riskImport1);
        }
    }

    @Override
    public Integer doChangeRes(RiimRiskImport riimRiskImport) {
        return riskImportMapper.updateByPrimaryKeySelective(riimRiskImport);
    }


    public String zhaunhuan(String goal) {
        String result = goal.replace("<", "&lt;");
        return result;
    }

    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * taskGuid 项目id(重点风险id)
     * context 审批意见
     * submitType 提交、回退、结束, 值：(submit, reject, end)
     */
    @Override
    public boolean updateStatus(Map<String, Object> params) {
        RiimRiskImport riskImport = new RiimRiskImport();
        String id = (String) params.get("bizGuid");
        String planStatus = (String) params.get("nextStatus");
        String planStatusName = (String) params.get("nextStatusName");
        riskImport = (RiimRiskImport) BeanUtils.updateBean(riskImport);
        riskImport.setId(id);
        riskImport.setPlanStatus(planStatus);
        riskImport.setPlanStatusName(planStatusName);

        if(params.get("quartzParam")!=null && "1".equals(params.get("quartzParam").toString())){
            if ("B06".equals(params.get("status"))) {
                //添加审核人
                riskImport.setGroupUserCode(params.get("currentExaminerCode").toString());
                riskImport.setGroupUserName(params.get("currentExaminerName").toString());
            } else if ("B02".equals(params.get("status"))) {
                //添加审批人
                riskImport.setDeptUserCode(params.get("currentExaminerCode").toString());
                riskImport.setDeptUserName(params.get("currentExaminerName").toString());
            }
        }else {
            if ("B06".equals(params.get("status"))) {
                //添加审核人
                riskImport.setGroupUserCode(getUser().getUserCode());
                riskImport.setGroupUserName(getUser().getUserDesc());
            } else if ("B02".equals(params.get("status"))) {
                //添加审批人
                riskImport.setDeptUserCode(getUser().getUserCode());
                riskImport.setDeptUserName(getUser().getUserDesc());
            }
        }

        update(riskImport);
        return true;
    }

    /**
     * status	当前节点状态
     * nextStatus	下一节点状态
     * nextStatusName	下一节点状态名称
     * acctYear	当前年度
     * quarterCurrent	当前季度
     * deptCode	填报人的部门编码
     * bizGuid 业务id
     * taskGuid 项目id(重点风险id)
     * context 审批意见
     * submitType 提交、回退、结束, 值：(submit, reject, end)
     */
    @Override
    public boolean doAfter(Map<String, Object> params) {
//        AsyncManager.me().execute(new TimerTask() {
//            @Override
//            public void run() {
                try {
                    String importId = (String) params.get("bizGuid");
                    String acctYear = (String) params.get("acctYear");
                    Map map = importService.importWord(importId);
                    if (map.isEmpty()) {
                        log.error("数据为空！");
                        throw new Exception("数据为空");
                    }
                    String sourceModel = "T_RIRE_RISK_WARNING_STATUS_" + acctYear;
                    freeMarkerController.exportPDF(map, "import.ftl", "zhongdianfengxian", importId, sourceModel, true);
                } catch (Exception e) {
                    log.error("生成实施方案pdf异常：" + e.getMessage());
                    return false;
                }
//            }
//        });
        return true;
    }

    private String advanceMechanismTemplate = "<w:p><w:pPr><w:pStyle w:val=\"2\"/><w:keepNext w:val=\"0\"/><w:keepLines w:val=\"0\"/><w:pageBreakBefore w:val=\"0\"/><w:widowControl w:val=\"0\"/><w:kinsoku/><w:wordWrap/><w:overflowPunct/><w:topLinePunct w:val=\"0\"/><w:autoSpaceDE/><w:autoSpaceDN/><w:bidi w:val=\"0\"/><w:adjustRightInd/><w:snapToGrid w:val=\"0\"/><w:spacing w:before=\"0\" w:beforeLines=\"0\" w:after=\"0\" w:afterLines=\"0\" w:line=\"400\" w:lineRule=\"exact\"/><w:ind w:right=\"0\" w:rightChars=\"0\"/><w:jc w:val=\"both\"/><w:textAlignment w:val=\"auto\"/><w:outlineLvl w:val=\"9\"/><w:rPr><w:rFonts w:hint=\"eastAsia\" w:ascii=\"仿宋_GB2312\" w:hAnsi=\"仿宋_GB2312\" w:eastAsia=\"仿宋_GB2312\"/><w:b w:val=\"0\"/><w:bCs w:val=\"0\"/><w:color w:val=\"000000\"/><w:sz w:val=\"24\"/><w:szCs w:val=\"24\"/><w:lang w:eastAsia=\"zh-CN\"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:hint=\"default\" w:ascii=\"仿宋_GB2312\" w:hAnsi=\"仿宋_GB2312\" w:eastAsia=\"仿宋_GB2312\" w:cs=\"仿宋_GB2312\"/><w:color w:val=\"000000\"/><w:sz w:val=\"24\"/><w:szCs w:val=\"24\"/><w:lang w:eastAsia=\"zh-CN\"/></w:rPr><w:t xml:space=\"preserve\">${advanceMechanism}</w:t></w:r></w:p>";
    private String trainNeedTemplate = "<w:p><w:pPr><w:pStyle w:val=\"2\"/><w:keepNext w:val=\"0\"/><w:keepLines w:val=\"0\"/><w:pageBreakBefore w:val=\"0\"/><w:widowControl w:val=\"0\"/><w:kinsoku/><w:wordWrap/><w:overflowPunct/><w:topLinePunct w:val=\"0\"/><w:autoSpaceDE/><w:autoSpaceDN/><w:bidi w:val=\"0\"/><w:adjustRightInd/><w:snapToGrid w:val=\"0\"/><w:spacing w:before=\"0\" w:beforeLines=\"0\" w:after=\"0\" w:afterLines=\"0\" w:line=\"400\" w:lineRule=\"exact\"/><w:ind w:right=\"0\" w:rightChars=\"0\"/><w:jc w:val=\"both\"/><w:textAlignment w:val=\"auto\"/><w:outlineLvl w:val=\"9\"/><w:rPr><w:rFonts w:hint=\"eastAsia\" w:ascii=\"仿宋_GB2312\" w:hAnsi=\"仿宋_GB2312\" w:eastAsia=\"仿宋_GB2312\" w:cs=\"仿宋_GB2312\"/><w:b w:val=\"0\"/><w:bCs w:val=\"0\"/><w:color w:val=\"000000\"/><w:sz w:val=\"24\"/><w:szCs w:val=\"24\"/><w:lang w:eastAsia=\"zh-CN\"/></w:rPr></w:pPr><w:r><w:rPr><w:rFonts w:hint=\"default\" w:ascii=\"仿宋_GB2312\" w:hAnsi=\"仿宋_GB2312\" w:eastAsia=\"仿宋_GB2312\" w:cs=\"仿宋_GB2312\"/><w:color w:val=\"000000\"/><w:sz w:val=\"24\"/><w:szCs w:val=\"24\"/><w:lang w:eastAsia=\"zh-CN\"/></w:rPr><w:t xml:space=\"preserve\">${trainNeed}</w:t></w:r></w:p>";

    /**
     * 转换生成word时的参数，解决换行问题，行首空格显示问题
     * @param param 模板中需要的参数
     * @param paramTemplate 模板字符串
     * @param target 参数占位符
     *
     */
    private String convertParam(String param, String paramTemplate, String target){
        if (StringUtils.isNotEmpty(param)) {
            StringBuilder result = new StringBuilder();
            String[] paramSplit = param.split("\n");
            for (String str : paramSplit) {
                result.append(paramTemplate.replace(target, str));
            }
            return result.toString();
        } else {
            return " ";
        }
    }

    @Override
    public void addDutyUser(SyncEmpleeEntitiy employee, RiimRiskImport riimRiskImport) throws Exception {
        riaaQuesInquiryService.addUserToSystem(employee, riimRiskImport.getDeptCode(), "TASK01");
    }


    /**
     * 进行数据验证  如果和表里已有的重复 则为false
     * @param risk
     * @return Boolean
     */
    public Boolean checkCopyImportRisk(RiimRiskImport risk){
            int total = riskImportMapper.checkCopyImportRisk(risk);
        return total == 0;
    }

	@Override
	@Transactional
	public void shiftDuty(String compCode, String newUserCode, String oldUserCode) {
		XtzyUser newUser = xtzyUserService.selectByName(newUserCode);

		RiimRiskImport param = new RiimRiskImport();
		param.setDutyUserCode(oldUserCode);
		param.setCompCode(compCode);
		List<RiimRiskImport> list = riskImportMapper.select(param);
		for(RiimRiskImport riskImport : list){
			riskImport.setDutyUserCode(newUserCode);
			riskImport.setDutyUserName(newUser.getUserDesc());
			riskImportMapper.updateByPrimaryKey(riskImport);
		}
	}

}
